package com.warm.system.service;

import com.warm.core.constant.Constants;
import com.warm.core.exception.user.UserPasswordNotMatchException;
import com.warm.core.exception.user.UserPasswordRetryLimitExceedException;
import com.warm.core.utils.MessageUtils;
import com.warm.pom.satoken.utils.LoginUtils;
import com.warm.select.api.RedisCache;
import com.warm.select.constant.CacheConstants;
import com.warm.system.api.domain.SysUser;
import com.warm.thread.manager.AsyncManager;
import com.warm.thread.manager.factory.AsyncFactory;
import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Inject;

/**
 * 登录密码方法
 *
 * @author warm
 */
@Component
public class SysPasswordService {
    @Inject
    private RedisCache redisCache;

    @Inject(value = "${user.password.maxRetryCount}")
    private int maxRetryCount;

    @Inject(value = "${user.password.lockTime}")
    private int lockTime;

    /**
     * 登录账户密码错误次数缓存键名
     *
     * @param username 用户名
     * @return 缓存键key
     */
    private String getCacheKey(String username) {
        return CacheConstants.PWD_ERR_CNT_KEY + username;
    }

    public void validate(String password, SysUser user) {
        String username = user.getUserName();
        Integer retryCount = redisCache.getCacheObject(getCacheKey(username), Integer.class);

        if (retryCount == null) {
            retryCount = 0;
        }

        if (retryCount >= maxRetryCount) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL,
                    MessageUtils.message("user.password.retry.limit.exceed", maxRetryCount, lockTime)));
            throw new UserPasswordRetryLimitExceedException(maxRetryCount, lockTime);
        }

        if (!LoginUtils.matchesPassword(password, user.getPassword())) {
            retryCount = retryCount + 1;
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL,
                    MessageUtils.message("user.password.retry.limit.count", retryCount)));
            redisCache.setCacheObject(getCacheKey(username), retryCount, lockTime * 60);
            throw new UserPasswordNotMatchException();
        } else {
            clearLoginRecordCache(username);
        }
    }

    public void clearLoginRecordCache(String loginName) {
        if (redisCache.hasKey(getCacheKey(loginName))) {
            redisCache.deleteObject(getCacheKey(loginName));
        }
    }
}
